import { useState, useRef, useEffect, KeyboardEvent, MouseEvent } from 'react'
import styled from 'styled-components'
import { Game, TGameStatus, ESnakeMoveDirection } from './reducer'

const Wrapper = styled.div`
  display: grid;
  place-items: center;
  min-height: 100vh;
  background-color: #334;
  color: white;

  & canvas {
    margin-top: 3rem;
    /* border:1px solid blue; */
    background-color: hsl(100, 70%, 20%);
  }
  & div.action {
    display: flex;
  }
`

const Button: React.FC<React.ButtonHTMLAttributes<HTMLButtonElement>>
= ({children, onClick}) => {
  const ref = useRef<any>(null)
  const clickHandler = (e:MouseEvent<HTMLButtonElement>) => {
    ref.current.blur();
    onClick?.(e);
  }
  return (
    <button ref={ref} onClick={clickHandler}>
      {children}
    </button>
  )
}
const instance:any = { };

export default function Demo () {
  const refCanvas = useRef<any>(null)
  const [status, setStatus] = useState<TGameStatus>('unknown');
  const ref = useRef<any>(null);

  const onStatusUpdated = (status: TGameStatus) => {
    setStatus(status)
  }
  useEffect(() => {
    const ctx = refCanvas.current?.getContext("2d");
    if (!!ctx) {
      instance.game = new Game(refCanvas, ctx, onStatusUpdated);
      instance.game.clearAll();
      instance.game.drawAll();
    }
  }, [])

  const onStart = () => { instance.game.start() }
  const onStop  = () => { instance.game.stop() }
  const onReset = () => { instance.game.reset() }
  const onKeyDown = (e: KeyboardEvent<HTMLElement>) => {
    switch(e.key) {
      case 'ArrowLeft':
        instance.game.setDirection(ESnakeMoveDirection.left);
        break;
      case 'ArrowRight':
        instance.game.setDirection(ESnakeMoveDirection.right);
        break;
      case 'ArrowUp':
        instance.game.setDirection(ESnakeMoveDirection.up);
        break;
      case 'ArrowDown':
        instance.game.setDirection(ESnakeMoveDirection.down);
        break;
    }
  };
  const onBlur = () => {
    ref.current.focus();
  }
  return (
    <Wrapper tabIndex={0} ref={ref} onKeyDown={onKeyDown} onBlur={onBlur}>
      <h1>Snake</h1>
      <div className='action'>
        { (status === 'ready') &&   <Button onClick={onStart}>Start</Button> }
        { (status === 'moving') &&  <Button onClick={onStop}>Stop</Button> }
        { (status === 'stopped') && <Button onClick={onReset}>Reset</Button>}
      </div>
      <canvas ref={refCanvas} width="100" height="100">
        !!! This browser doesn't support canvas !!!
      </canvas>
    </Wrapper>
  )
}
